package com.useeinfo.oa.modules.wuHanCommon.base.biz;

import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.CommonSugar;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.biz.MessageBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.enums.MessageTypeEnum;
import com.useeinfo.oa.modules.repair.biz.AutomaticRepairBiz;
import com.useeinfo.oa.modules.security.biz.UserDeviceBiz;
import com.useeinfo.oa.modules.threadUtil.ThreadUtils;
import com.useeinfo.oa.modules.wuHanCommon.base.dao.WarningDao;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.Warning;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.WarningDetail;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.WarningGroup;
import com.useeinfo.oa.modules.wuHanCommon.base.entity.WuHanPoint;
import com.useeinfo.oa.modules.wuHanCommon.base.result.ResultDto_Wh;
import com.useeinfo.oa.modules.wuHanCommon.base.result.ResultUtil_Wh;
import com.useeinfo.oa.modules.wuHanCommon.base.result.enums.ResultEnums_Wh;
import com.useeinfo.oa.modules.wuHanCommon.base.vo.WarningDeta;
import com.useeinfo.oa.modules.wuHanCommon.base.vo.WarningError;
import com.useeinfo.oa.modules.wuHanCommon.base.vo.WarningRealtimeVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class WarningBiz extends CrudBiz<WarningDao, Warning> {

    private final static Boolean productionMode = "true".equals(Configuration.getConfigurationByName("productionMode"));

    @Autowired
    private WuHanPointBiz wuHanPointBiz;
    @Autowired
    private WarningDetailBiz warningDetailBiz;
    @Autowired
    private WarningGroupBiz warningGroupBiz;
    @Autowired
    private UserDeviceBiz userDeviceBiz;
    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private AutomaticRepairBiz automaticRepairBiz;
    @Autowired
    private MessageBiz messageBiz;

    /**
     * 开始保存警告数据
     *
     * @param warningDetas
     * @return
     */
    public synchronized ResultDto_Wh warningCreate(List<WarningDeta> warningDetas) {
        if (CollectionUtils.isEmpty(warningDetas)) {
            return ResultUtil_Wh.error("无数据");
        }
        List<Warning> warnings = new ArrayList<>();
        List<WarningError> warningErrors = new ArrayList<>();
        StringBuilder errAllmsg = new StringBuilder();
        //循环所有的警告明细
        for (WarningDeta warningDeta : warningDetas) {
            if (!"1".equals(warningDeta.getWarningStatus())) {//状态是1的才是报警，才会保存
                continue;
            }
            StringBuilder errmsg = new StringBuilder();
            Warning warning = getWarningEntityByWarningId(warningDeta.getWarningId());
            if (warning == null) {
                warning = new Warning();
            }
            //警告数据转换
            ResultDto_Wh resultDto_wh = coverWarning(warning, warningDeta);
            if (resultDto_wh.getErr() != ResultEnums_Wh.SUCCESS.getCode()) {
                errmsg.append(resultDto_wh.getMsg()).append(",");
            }
            if (CollectionUtils.isNotEmpty(warningDeta.getPoints())) {
                for (String point : warningDeta.getPoints()) {
                    //查询点位是否存在
                    WuHanPoint wuHanPoint = wuHanPointBiz.getWuHanPointByName(point);
                    if (wuHanPoint == null) {
                        errmsg.append(point).append("点位不存在").append(",");
                    }
                    warning.getWarningDetails().add(new WarningDetail(wuHanPoint));
                }
            }
            errAllmsg.append(errmsg);
            if (StringUtils.isNotBlank(errmsg.toString())) {
                warningErrors.add(new WarningError(warningDeta.getWarningId(), errmsg.toString()));
                continue;
            }
            warnings.add(warning);
        }
        if (CollectionUtils.isNotEmpty(warningErrors)) {
            //存在错误数据，将错误信息返回
            return ResultUtil_Wh.error(errAllmsg.toString(), warningErrors);
        }
        //信息没问题，开始保存数据
        for (Warning warning : warnings) {
            boolean flag = true;
            if (warning.getId() != null) {
                flag = false;
            }
            //保存警告数据
            this.addOrUpdate(warning);
            if (flag && productionMode) {//只有警告是新增的才发消息，其余为更新警告的时间的，不需要推送
                //保存警告点位数据
                warning.getWarningDetails().forEach(warningDetail -> {
                    warningDetail.setWarning(warning);
                    warningDetailBiz.addOrUpdate(warningDetail);
                    //开始保存到报修单中
                    Long automaticEnterpriseId = StringConverters.ToLong(Configuration.getConfigurationByName("automaticEnterpriseId"));
                    Enterprise enterprise = enterpriseBiz.findModel(automaticEnterpriseId);
                    if (automaticRepairBiz.warningSaveToRepairOrder(warningDetail, enterprise)) {
                        //保存成功，开始推送消息数据
                        WarningGroup warningGroup = warning.getWarningGroup();
//                        String message = "点位值:" + warningDetail.getWuHanPoint().getName() + ",规则描述:" + warning.getContent();
                        ThreadUtils.sendDeviceMessages(userDeviceBiz.getUserDeviceListByWarningGroupId(warningGroup), warning.getContent(), MessageTypeEnum.AUTO, messageBiz, null, "");
                    }
                });
            }
        }
        return ResultUtil_Wh.success();
    }

    /**
     * 转换警告数据
     *
     * @param warning     警告表
     * @param warningDeta 点位数据
     * @return
     */
    private ResultDto_Wh coverWarning(Warning warning, WarningDeta warningDeta) {
        warning.setContent(warningDeta.getContent());
        warning.setLevel(warningDeta.getLevel());
        warning.setStartTime(StringConverters.ToDateTime(warningDeta.getStartTime()));
        warning.setSystem(warningDeta.getSystem());
        warning.setLastSeconds(StringConverters.ToDouble(warningDeta.getLastSeconds()).longValue());
        warning.setOtherWarningId(warningDeta.getWarningId());
        warning.setWarningStatus(StringConverters.ToInteger(warningDeta.getWarningStatus()));
        warning.setPosition(warningDeta.getPosition());
        warning.setBindPointValue(warningDeta.getBindPointValue());
        warning.setInfoDetail(warningDeta.getInfoDetail());
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("code", CommonSugar.getTypedDefault(warningDeta.getGroup(), "-1"));
        List<WarningGroup> warningGroups = warningGroupBiz.findList(queryParam);
        if (CollectionUtils.isEmpty(warningGroups)) {
            return ResultUtil_Wh.error("报警组：" + warningDeta.getGroup() + "不存在");
        }
        warning.setWarningGroup(warningGroups.get(0));
        return ResultUtil_Wh.success();
    }

    /**
     * 根据warningId查询是否存在
     *
     * @param warningId
     * @return
     */
    private Boolean getWarningByWarningId(String warningId) {
        if (StringUtils.isBlank(warningId)) {
            return false;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("otherWarningId", warningId);
        List<Warning> warnings = this.findList(queryParam);
        return CollectionUtils.isEmpty(warnings);
    }

    /**
     * 根据warningId查询是否存在
     *
     * @param warningId
     * @return
     */
    private Warning getWarningEntityByWarningId(String warningId) {
        if (StringUtils.isBlank(warningId)) {
            return null;
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("otherWarningId", warningId);
        List<Warning> warnings = this.findList(queryParam);
        if (CollectionUtils.isEmpty(warnings)) {
            return null;
        }
        return warnings.get(0);
    }


    /**
     * 自动抄表信息
     *
     * @param warningRealtimeVO
     * @return
     */
    public synchronized ResultDto_Wh dataUploadToServer(WarningRealtimeVO warningRealtimeVO) {

        return ResultUtil_Wh.success();
    }
}
